package com.tomcat;

import com.tomcat.mapper.Host;
import com.tomcat.mapper.Mapper;
import com.tomcat.server.RequestProcessor;
import com.tomcat.server.RequestThreadPool;
import com.tomcat.utils.ParsingServer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * desc: 启动类 入口
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 23/9/2020
 */
public class Bootstrap {
    private static Integer PORT;

    private static Mapper mapper = new Mapper();

    private static String appBase;

    /**
     * 建立连接，封装请求处理器，交给线程池管理
     * @throws Exception 异常
     */
    public static void start() throws Exception {
        // 创建socket连接
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("Mini tomcat start...");
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapper, appBase);
            // 使用线程池来管理RequestProcessor
            RequestThreadPool.getThreadPool().execute(requestProcessor);
        }

    }

    /**
     * 初始化容器
     */
    private static void load() {
        InputStream resourceAsStream = Bootstrap.class.getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            Element service = (Element) rootElement.selectSingleNode("Service");
            Element connector = (Element) service.selectSingleNode("Connector");
            String port = connector.attributeValue("port");
            PORT = Integer.parseInt(port);
            Element engine = (Element) connector.selectSingleNode("Engine");
            Element host = (Element) engine.selectSingleNode("Host");
            String name = host.attributeValue("name");
            appBase = host.attributeValue("appBase");
            // 解析appBase文件夹下的所有项目
            ParsingServer parsingServer = new ParsingServer(appBase, new Host(name, Integer.parseInt(port)));
            parsingServer.parsingContent();
            // 获取mapper
            mapper = parsingServer.getMapper();

        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        load();
        start();
    }
}
